package com.crm.customer.service;

import com.crm.common.mapper.CustomerMapper;
import com.crm.common.pojo.Customer;
import com.crm.global.exception.CrmException;
import com.crm.global.exception.ExceptionEnum;
import com.crm.id.increment.IdWorker;
import com.crm.mybatis.separation.Read;
import com.crm.mybatis.separation.Write;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class CustomerService{
    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private  LinkmanService linkmanService;

    @Autowired
    private ActivityService activityService;

    @Read
    public PageInfo<Customer> findAll(int page, int size, Customer customer) {
        PageHelper.startPage(page,size);

        customer = customer != null ? customer : new Customer();

        Example example = new Example(Customer.class);

        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(customer.getName())) {
            criteria.orLike("name","%" + customer.getName() + "%");
        } else if(StringUtils.isNotBlank(customer.getAddress())) {
            criteria.orLike("address",customer.getAddress());
        } else if (customer.getLevel() != null) {
            criteria.orEqualTo("level",customer.getLevel());
        }

        List<Customer> customers = customerMapper.selectByExample(example);
        return new PageInfo<>(customers);
    }


    @Write
    public void saveOrUpdate(Customer customer) {
        if (customer == null) {
            throw new CrmException(ExceptionEnum.PARAM_IS_NULL);
        }
        if (customer.getId() == null) {
            customer.setId(new IdWorker().nextId());
            customerMapper.insert(customer);
        } else {
            customerMapper.updateByPrimaryKey(customer);
        }
    }

    @Write
    public void delete(Long id) {
        /*
         *  删除客户信息，客户的联系人和交往记录也都需要删除
         *  注意：
         *       当删除客户时，不会自动删除联系人和交往记录
         *       因为表和表之间没有存在物理外键，而都是逻辑外键
         *       所以需要开发人员进行详细的控制关系
         *       现在没有实现，等实现了联系人和交往记录再回头补充完成
         *
         */
        customerMapper.deleteByPrimaryKey(id);
        linkmanService.deleteByCustomerId(id);
        activityService.deleteByCustomerId(id);
    }
}
